const { ipcMain,BrowserWindow } = require('electron')
const WinState = require('electron-win-state').default
const path = require('path')
const saveas = require('./saveas')

const cssText = `width: 60px;height: 30px;background-color: cornflowerblue;border-radius: 5px;text-align: center;line-height: 30px;position: fixed;right: 20px;bottom: 50px;color: #fff;z-index: 1000;cursor: pointer;`

const js = `
const div = document.createElement('div')
div.id = 'readit-button'
div.innerHTML = '关闭窗口'
document.body.appendChild(div)
div.style.cssText = '${cssText}'
div.addEventListener('click',()=>{
  window.myApi.closeNewWindow()
})
`
let win = null

ipcMain.handle('on-new-window-event',(e,url)=>{
  const winState = new WinState({
    defaultWidth:1200,
    defaultHeight:800,
    electronStoreOptions:{name:'new-window'}
  })
  win = new BrowserWindow({
    ...winState.winOptions,
    show:false,
    // 一个进程对应一个preload文件
    webPreferences:{
      preload:path.resolve(__dirname,'./preload')
    }
  })
  win.on('ready-to-show',()=>{
    win.show()
  })
  win.loadURL(url)
  win.webContents.openDevTools()
  winState.manage(win)
  //页面中注册代码
  win.webContents.executeJavaScript(js).catch(()=>{})
  win.webContents.on('context-menu',(e,args)=>{
    saveas(args.srcURL)
  })
})

ipcMain.handle('close-new-window',()=>{
  win.close()
})
